<?php
class PositionAction extends TransportcommonAction {
    public function index(){
        $inputs = I();
        $model = new Model();
        $userInfo = $_SESSION["_USER_INFO"];
        
        //判断用户所属城市地区，对前台页面做不同处理
        if($userInfo['area_id']==2){
            $this->areaChk = "北京市";
        }else{
            $this->areaChk = "山东省";
        }
        //获取分组的车辆列表
        if($inputs['op'] == 'getCars'){
            $groupId = $inputs['group_id'];
            if($groupId != '0'){
                //判断是否有子分组
                if($userInfo['role_id']!=87){
                    $arr_sql = "select tg.id,group_name from `transport_group` tg
                            join `transport_group_role` tgr on tgr.group_id = tg.id
                            where pid=".$groupId." and tgr.role_id = {$userInfo['role_id']};";
                }else{
                    $arr_sql = "select tg.id,group_name from `transport_group` tg
                            where pid=".$groupId.";";
                }
                $arr_result = $model->query($arr_sql);
                if(count($arr_result)){
                    $data['info'] = 'group';
                    $data['arr'] = $arr_result;
                    echo json_encode($data);die;//存在子分组，直接返回
                }
            }
//不存在子分组，直接返回车辆
            if($userInfo['role_id']!=87){
                $cars_sql = "select aob.plate_no,au.username,aob.obd_no,tgm.remark from product p
                join auto_obd_bind aob on aob.obd_no = p.snid
                left join auto_user au on au.id = aob.userid
                left join transport_group_map tgm on tgm.obd_no = aob.obd_no
                left join transport_group tg on tg.id = tgm.group_id
                join transport_group_role tgr on tgm.group_id = tgr.group_id
                where tgr.role_id = {$userInfo['role_id']} ";
            }else{
                $cars_sql = "select aob.plate_no,au.username,aob.obd_no,tgm.remark from product p
                join auto_obd_bind aob on aob.obd_no = p.snid
                left join auto_user au on au.id = aob.userid
                left join transport_group_map tgm on tgm.obd_no = aob.obd_no
                left join transport_group tg on tg.id = tgm.group_id
                where p.uid = {$userInfo['id']}";
            }
            
            if($groupId!=0){
                $cars_sql .= " and tgm.group_id = {$inputs['group_id']}; ";
            }else{
                $cars_sql .= " and aob.obd_no not in(select obd_no from product p join transport_group_map tgm on p.snid = tgm.obd_no where tgm.group_id>0); ";
            }
            $cars_result = $model->query($cars_sql);
//            $obd_arr[] = "H_heartbeat";
            foreach($cars_result as $key => $value){
                $obd_arr[] = $value['obd_no'];
            }
            $obd = array_chunk($obd_arr,100);
            if(!empty($cars_result))
                $cars_result[0]['voice_group_all'] = 0;//组默认不显示公聊按钮
            foreach($obd as $item){
                //获取当前obd设备状态
    //            $status_url = 'http://';//----------测试地址
                $status_url = 'https://';//----------正式地址
                $status_data['obdids'] = $item;
                $status_result = json_decode(uploadByCURL(json_encode($status_data),$status_url),true);
                if($status_result['result'] == 0){
                     foreach($cars_result as $key => $value){
                         foreach($status_result['infos'] as $k => $v){
                             if($k == $value['obd_no']){
                                 if($v['isstop'] == 0){//点火状态
                                     $cars_result[$key]['car_status'] = '0';//运行状态
                                     $cars_result[$key]['isstop'] = 0;
                                     $cars_result[0]['voice_group_all'] = 1;
                                 }else{
                                     $cars_result[$key]['car_status'] = '1';//停运状态
                                     $cars_result[$key]['isstop'] = 1;
                                 }
                                 if($v['last_start_time_int'] < time()-180){//如果3分钟没收到心跳
                                     $cars_result[$key]['car_status'] = '2';//离线状态
                                 }
                             }
                         }
                     }
                }else{
                    foreach($cars_result as $key => $value){
                        $cars_result[$key]['car_status'] = '2';//离线
                    }
                }

                //获取当前obd是否支持语音对讲   zsn 20170710 14:29
                $status_url2 = 'https://';//----------正式地址
                // $status_url2 = 'http://';//----------测试地址
                $status_data2['obdids'] = $item;
                $status_result2 = json_decode(uploadByCURL(json_encode($status_data2),$status_url2),true);
                $cars_result[0]['voice_group'] = 0;//组默认不支持
                foreach($status_result2['list'] as $val){
                    if($val['stat'] == 0){//组支持对讲
                         $cars_result[0]['voice_group'] = 1;
                         break;
                    }
                }  
            }
            // var_dump($cars_result);
            

            //获取obd最后位置上报信息
            $timestamp = time();
            $token = 'A#tomic@Soner'.$timestamp;
            if(!empty($obd_arr))
                $result = uploadByCURL(json_encode(array('obdids' =>$obd_arr,'token' =>$token)),"https://");
            $temp = json_decode($result,true);
            foreach($cars_result as $key => $value){
                foreach($temp['list'] as $k1 => $v1){
                    if($value['obd_no'] == $v1['id']){
                        $mapPosition = $temp["list"][$k1]["lg"]?explode(",",$temp["list"][$k1]["lg"]):explode(",",$temp["list"][$k1]["g"]);
                        $position = $temp['list'][$k1]['rs']?$temp['list'][$k1]['rs']:'';
                        $lng = $mapPosition[1];  //存储一份 经度纬度位置信息，当接口没有返回值时引用
                        $lat = $mapPosition[0];
                        $cars_result[$key]['position'] = $temp['list'][$k1]['rs']?$temp['list'][$k1]['rs']:'';//车辆当前地理位置
                        $cars_result[$key]['lng'] = $mapPosition[1];//车辆当前坐标经度
                        $cars_result[$key]['lat'] = $mapPosition[0];//车辆当前坐标纬度
                        $cars_result[$key]['lastTime'] = $temp['list'][$k1]['lt']?urldecode($temp['list'][$key]['lt']):urldecode($temp['list'][$k1]['t']);//车辆当前坐标汇报时间
                    }
                }
                
            }
            foreach ($cars_result as $k2 => $v2){
                if(!isset($v2['lng'])){
                    $cars_result[$k2]['lng'] = $lng;
                    $cars_result[$k2]['lat'] = $lat;
                    $cars_result[$k2]['position'] = $position;
                }
            }
            // var_dump($cars_result);
            //信息有：plate_no,username,obd_no,isstop,remark,position,lng,lat,car_status，lastTime
            $data['info'] = 'car';
            if($groupId == 220){
                $popout_url = "http://";
                $zf_gps = json_decode(file_get_contents($popout_url),true);
                $gps = explode(',',$zf_gps['gps']);
                $cars_result[0]['obd_no'] = "zf1530027";
                $cars_result[0]['plate_no'] = "执法B2052";
                $cars_result[0]['camera'] = 'zf';
                $cars_result[0]['username'] = '15210295942';
                $cars_result[0]['lng'] = $gps[1];
                $cars_result[0]['lat'] = $gps[0];
                $cars_result[0]['isstop'] = 1;
                $cars_result[1]['car_status'] = 4;
                $cars_result[0]['hc_source_url'] = 'http://';
                $cars_result[0]['hc_camid'] = '36627497117180031_48';
                $cars_result[0]['car_status'] = 4;
                $cars_result[0]['lastTime'] = date('Y-m-d H:i:s',time());

                $popout_url = "http://";
                $zf_gps = json_decode(file_get_contents($popout_url),true);
                $gps = explode(',',$zf_gps['gps']);
                $cars_result[1]['obd_no'] = "zf1898249";
                $cars_result[1]['plate_no'] = "执法A1728";
                $cars_result[1]['camera'] = 'zf';
                $cars_result[1]['username'] = '15300278249';
                $cars_result[1]['hc_gps'] = '36.86342,117.514159';
                $cars_result[1]['isstop'] = 1;
                $cars_result[1]['lng'] =  $gps[1];
                $cars_result[1]['car_status'] = 4;
                $cars_result[1]['lat'] = $gps[0];
                $cars_result[1]['hc_hw_code'] = 'G20';
                $cars_result[1]['lastTime'] = date('Y-m-d H:i:s',time());      
            }
            
            $data['arr'] = $cars_result;
            echo json_encode($data);die;
        }
        if($userInfo['role_id'] != 87){
            $result = M("transport_group")->join(" tg join transport_group_role tgr on tg.id = tgr.group_id ")->where("tg.status=0 and tg.pid=0 and tgr.role_id = {$userInfo['role_id']}")->field('tg.id,tg.group_name')->select();
        }else{
            $result = M("transport_group")->where("status=0 and uid=".$userInfo['id']." and pid=0")->field('id,group_name')->select();
        }
        $this->groupList = $result?json_encode($result):'';
        $this->display();
    }

//其他页面定位过来(已加)
    public function openPosition(){
        $inputs = I();
        $model = new Model();
        $userInfo = $_SESSION["_USER_INFO"];
        //从其他页面定位过来
        if($inputs['op'] == 'getPosition'){
            $obd_no = $inputs['obd_no'];
            $sql = "select obd_no,group_id from `transport_group_map` where obd_no = ".$obd_no.";";
            $result = $model->query($sql);
            $arr[] = $obd_no;
            $group_id = $result[0]['group_id'];
            $arr[] = $group_id;
            while($group_id != 0){
                $result = $model->query("select pid from `transport_group` where id=".$group_id.";");
                $arr[] = $result[0]['pid'];
                $group_id = $result[0]['pid'];
            }
            $arr = array_reverse($arr);//从0开始，往下依次是分组id，最后一个是obd_no
            if(count($arr) > 2){
                array_shift($arr);
            }
            $this->group_arr = json_encode($arr);
            $this->obd_no = $obd_no;
        }
        if($userInfo['role_id'] !=87){
            $result = M("transport_group")->join(" tg join transport_group_role tgr on tg.id = tgr.group_id ")->where("tg.status=0 and tg.pid=0")->field('tg.id,tg.group_name')->select();
        }else{
            $result = M("transport_group")->where("status=0 and uid=".$userInfo['id']." and pid=0")->field('id,group_name')->select();
        }
        
        $this->groupList = $result?json_encode($result):'';
        $this->display("index");
    }

    //搜索单个车辆信息（已加）
    public function getOne(){
        $inputs = I();
        $model = new Model();
        $userInfo = $_SESSION["_USER_INFO"];
        $searchValue = trim($inputs['searchValue']);
        // $sql = "SELECT aob.obd_no,IF(group_id IS NULL,0,group_id) group_id  
        //         FROM `auto_obd_bind` aob 
        //         LEFT JOIN `transport_group_map`tgm ON tgm.obd_no = aob.obd_no 
        //         WHERE aob.obd_no LIKE '%".$searchValue."%' OR aob.plate_no LIKE '%".$searchValue."%';";
        $time = $inputs['time'];
        $group = $inputs['group'];
        if($time&&$group){
            $sql = "SELECT aob.obd_no,IF(group_id IS NULL,0,group_id) group_id  
                                FROM `auto_obd_bind` aob 
                                LEFT JOIN `transport_group_map`tgm ON tgm.obd_no = aob.obd_no 
                                WHERE aob.obd_no LIKE '%".$searchValue."%' OR aob.plate_no LIKE '%".$searchValue."%';";
            $result = $model->query($sql);
            foreach($result as $item){
                $status_url = 'https://';//----------正式地址
                $status_data['obdids'][] = $item['obd_no'];
                $status_result = json_decode(uploadByCURL(json_encode($status_data),$status_url),true);
                // var_dump($status_result);
                if($status_result['result'] == 0){
                     foreach($status_result['infos'] as $k => $v){
                         if($k == $item['obd_no']){
                             if($v['isstop'] != 0){
                                 $timestamp = $v['last_start_time']?strtotime($v['last_start_time']):0;
                                 $off_time = time() - $timestamp;
                                 if($off_time < intval($time)){
                                    if($item['group_id']!=$group){
                                        echo json_encode(array('status'=>false));die;
                                    }
                                 }
                             }
                         }
                     }
                 }
            }
        }elseif($time){
            $sql = "SELECT aob.obd_no,IF(group_id IS NULL,0,group_id) group_id  
                                FROM `auto_obd_bind` aob 
                                LEFT JOIN `transport_group_map`tgm ON tgm.obd_no = aob.obd_no 
                                WHERE aob.obd_no LIKE '%".$searchValue."%' OR aob.plate_no LIKE '%".$searchValue."%';";
            $result = $model->query($sql);
            foreach($result as $item){
                $status_url = 'https://';//----------正式地址
                $status_data['obdids'][] = $item['obd_no'];
                $status_result = json_decode(uploadByCURL(json_encode($status_data),$status_url),true);
                // var_dump($status_result);
                if($status_result['result'] == 0){
                     foreach($status_result['infos'] as $k => $v){
                         if($k == $item['obd_no']){
                             if($v['isstop'] != 0){
                                 $timestamp = $v['last_start_time']?strtotime($v['last_start_time']):0;
                                 $off_time = time() - $timestamp;
                                 if($off_time < intval($time)){
                                    echo json_encode(array('status'=>false));die;
                                 }
                             }
                         }
                     }
                 }
            }
        }elseif(!empty($group)&&$group!=1){
            $sql = "SELECT aob.obd_no,IF(group_id IS NULL,0,group_id) group_id  
                    FROM `auto_obd_bind` aob 
                    LEFT JOIN `transport_group_map`tgm ON tgm.obd_no = aob.obd_no 
                    WHERE tgm.group_id = ".$group." AND (aob.obd_no LIKE '%".$searchValue."%' OR aob.plate_no LIKE '%".$searchValue."%');";
            $result = $model->query($sql);
        }else{
            $sql = "SELECT aob.obd_no,IF(group_id IS NULL,0,group_id) group_id  
                    FROM `auto_obd_bind` aob 
                    LEFT JOIN `transport_group_map`tgm ON tgm.obd_no = aob.obd_no 
                    WHERE aob.obd_no LIKE '%".$searchValue."%' OR aob.plate_no LIKE '%".$searchValue."%';";
            $result = $model->query($sql);
        }
         // echo $model->getLastSQL();
        if(!count($result)){
            echo json_encode(array('status'=>false));die;
        }
        $arr[] = $result[0]['obd_no'];
        $group_id = $result[0]['group_id'];
        $arr[] = $group_id;
        while($group_id != 0){
            $result = $model->query("select pid from `transport_group` where id=".$group_id.";");
            $arr[] = $result[0]['pid'];
            $group_id = $result[0]['pid'];
        }
        $arr = array_reverse($arr);//从0开始，往下依次是分组id，最后一个是obd_no
        if(count($arr) > 2){
            array_shift($arr);
        }
        $data['status'] = true;
        $data['arr'] = $arr;
        echo json_encode($data);die;
    }

    //显示可移动的分组列表（已加）
    public function selectGroup(){
        $inputs = I();
        $id = $inputs['group_id'];//鼠标滑过的分组id
        $car_group_id = $inputs['car_group_id'];//车辆所在的group_id
        $userInfo = $_SESSION["_USER_INFO"];
        $model = M("transport_group");
        $groups = $model->where("pid=".$id." and uid=".$userInfo['id'])->field('id,group_name')->select();
        foreach($groups as $key => $value){
            if($value['id'] == $car_group_id){
                unset($groups[$key]);
            }
        }
        echo json_encode($groups);die;
    }

    //添加车辆分组（已加）
    function  add_groupHandle(){
        $inputs = I();
        $userInfo = $_SESSION["_USER_INFO"];
        $add_groupName = urldecode(trim($inputs['groupName']));
        if(empty($add_groupName)){
            echo json_encode(array("status"=>false));exit(0);
        }
        $transportGroupModel = M('transport_group');
        $value['group_name'] = $add_groupName;
        $value['status'] = 0;//默认可以使用
        $grade = $userInfo['grade'];//用户等级：2是管理员，3是子账户
        if($grade > 2){
            $create_username = $userInfo['create_by'];//string类型
            $p_user_id = M("rbac_user")->where("account='".$create_username."'")->getField('id');//获取创建者id
            $value['uid'] = $p_user_id;//默认可以使用
        }else{
            $value['uid'] = $userInfo['id'];//默认可以使用
        }
        $value['admin_id'] = $userInfo['id'];
        $value['inputtime'] = date("Y-m-d H:i:s",time());
        $result = $transportGroupModel->add($value);
        if($result){
            $role_id = $userInfo['role_id'];
            M("transport_group_role")->add(array('role_id'=>$role_id,'group_id'=>$result));
            $data['status'] = true;
            $data['group_id'] = $result;
            $data['group_name'] = $add_groupName;
        }else{
            $data['status'] = false;
        }
        echo json_encode($data);die;
    }

    //更改分组名称（已加）
    function update_groupNameHandle(){
        $inputs = I();
        $new_name = urldecode(trim($inputs['new_name']));
        if(empty($new_name)){
            echo json_encode(array("status"=>false));exit(0);
        }
        $groupId = $inputs['groupId'];
        $transportGroupModel = M('transport_group');
        $value['group_name'] = $new_name;
        $value['inputtime'] = date("Y-m-d H:i:s",time());
        $result = $transportGroupModel->where('id='.$groupId)->save($value);
        if($result){
            $data['status'] = true;
        }else{
            $data['status'] = false;
        }
        echo json_encode($data);die;
    }

    //点击车辆标识，弹出信息框（已加）
    function currentInfo(){
        $inputs = I();
        $extData = urldecode($inputs['extData']);
        //信息有：plate_no,username,obd_no,isstop,transport_remark,position,lng,lat,car_status,lastTime
        $tmp_arr = explode(",",$extData);
        //当前街道位置(lng在前，lat在后)
        $address = json_decode(file_get_contents("https://"),true);
        if($address['status']==1&&!empty($address['regeocode']['formatted_address'])){
            if(!empty($address['regeocode']['addressComponent']['township'])){
                if(!empty($address['regeocode']['addressComponent']['streetNumber']['street'])){
                    $laststreet['address'] =  $address['regeocode']['addressComponent']['township'].''.$address['regeocode']['addressComponent']['streetNumber']['street'];
                }else{
                    $laststreet['address'] =  $address['regeocode']['addressComponent']['township'];
                }
            }else{
                if(!empty($address['regeocode']['addressComponent']['streetNumber']['street'])){
                    $laststreet['address'] =  $address['regeocode']['addressComponent']['streetNumber']['street'];
                }else{
                    $laststreet['address'] =  '未知';
                }
            }
        }else{
            $laststreet['address'] = '未知';
        }

        $obd = $tmp_arr[2];

        //图片抓拍坐标点--------这里等待新的接口（目前暂用旧逻辑）

//        $lastTime = $tmp_arr[9];//最近坐标汇报时间
        if(!empty($obd))        
            $result = uploadByCURL(json_encode(array('obdids' =>array($obd),'token' => 'token')),"https://");
        $temp = json_decode($result,true);
        $imageGps = explode(",",$temp['list'][0]['g']);
        $imageGps_lat = $imageGps[0];
        $imageGps_lng = $imageGps[1];
        if(strtotime($temp['list'][0]['t'])>strtotime("-2 hours")){
            $imageUrl = $temp['list'][0]['u'];//图片地址
            $imageTime = $temp['list'][0]['t'];//图片时间
            $cityCode = $temp['list'][0]['c'];//城市代码
        }else{
            $imageUrl = "";
            $imageTime = "";
        }
        $lastTime = $temp['list'][0]['lt'];
        //图片拍摄位置
        $address = json_decode(file_get_contents("http:/"),true);
        if($address['status']==1&&!empty($address['regeocode']['formatted_address'])){
            if(!empty($address['regeocode']['addressComponent']['township'])){
                if(!empty($address['regeocode']['addressComponent']['streetNumber']['street'])){
                    $image['street'] =  $address['regeocode']['addressComponent']['township'].''.$address['regeocode']['addressComponent']['streetNumber']['street'];
                }else{
                    $image['street'] =  $address['regeocode']['addressComponent']['township'];
                }
            }else{
                if(!empty($address['regeocode']['addressComponent']['streetNumber']['street'])){
                    $image['street'] =  $address['regeocode']['addressComponent']['streetNumber']['street'];
                }else{
                    $image['street'] =  '未知';
                }
            }
        }else{
            $image['street'] = '未知';
        }

        //获取当前obd设备状态
        $obd_arr[] = $obd;
//        $status_url = 'http://';//----------测试地址
            $status_url = 'https://';//----------正式地址
        $status_data['obdids'] = $obd_arr;
        $status_result = json_decode(uploadByCURL(json_encode($status_data),$status_url),true);
        // var_dump($status_result);
        if($status_result['result'] == 0){
            $json[0]['voice_group'] = 0;//默认不显示按钮
            if($status_result['infos'][$obd]['isstop'] == 0){
                $json['car_status'] = '0';//运行状态
                $json[0]['voice_group'] = 1;
            }else{
                $json['car_status'] = '1';//停运状态
            }
            if($status_result['infos'][$obd]['last_start_time_int'] < time()-172800){//如果3分钟没收到心跳
                $json['car_status'] = '2';//离线状态
            }
        }else{
            $json['car_status'] = '2';//离线状态
        }
        //获取监控状态
        $cam_stat_arr = $status_result['infos'][$obd]['cam_stat'];
        if($cam_stat_arr){
            foreach($cam_stat_arr as $key => $value){
                //获取redis摄像头状态
               $cam_status = json_decode(file_get_contents("https://"),true);  //{"result":1,"streamlive":1,"cmdlive":0}
               if($cam_status['result']==0){
                   $cam_stat[] = array("is_online"=>"true","camid"=>$value['id']);
               }else if($cam_status['result']==1){
                   $cam_stat[] = array("is_online"=>"false","camid"=>$value['id']);
               }
                // if($json['car_status'] == '0' &&$value['isValid']&&$value['status']==0){
                //  $cam_stat[] = array("is_online"=>"true","camid"=>$value['id']);
                // }else{
                //  $cam_stat[] = array("is_online"=>"false","camid"=>$value['id']);
                // }
            }
        }else{
            
            if($obd == 'zf1898249' || $obd =='zf1530027'){
                $cam_stat[] = array("is_online"=>"true","camid"=>$value['id']);
                
            }else{
                $cam_stat[] = array("is_online"=>"false");
            }
        }


//      //获取摄像头状态
//        $cam_res = json_decode(file_get_contents($url),true);
//        if($cam_res['camid']){
//            foreach($cam_res['camid'] as $key => $value){
//                //获取redis摄像头状态
//                $cam_status = json_decode(file_get_contents(""),true);  //{"result":1,"streamlive":1,"cmdlive":0}
//                if($cam_status['result']==0){
//                    $cam_stat[] = array("is_online"=>"true","camid"=>$value);
//                }else if($cam_status['result']==1){
//                    $cam_stat[] = array("is_online"=>"false","camid"=>$value);
//                }
//            }
//        }else{
//            $cam_stat[] = array("is_online"=>"false");
//        }
        
        //改变redis中车辆是否支持对讲，供测试用
// $status_url123 = '';//----------正式地址
//         // $status_url3 = 'http://';//----------测试地址
//         $status_data123['obdid'] = '359769020680895';
//         $status_data123['camid'] = 'camid2';
//         $status_data123['stat'] = 0;
//         $status_result123 = json_decode(uploadByCURL(json_encode($status_data123),$status_url123),true);
// var_dump($status_result123);die();

        //获取当前obd是否支持语音对讲   zsn 20170710 14:29
        $status_url3 = 'https://';//----------正式地址
        // $status_url3 = 'http://';//----------测试地址
        $status_data3['obdids'] = $obd_arr;
        $status_result3 = json_decode(uploadByCURL(json_encode($status_data3),$status_url3),true);
        if($status_result3['list'][0]['stat'] == 0){//支持对讲
            $voice_status = 1;
        }else{
            $voice_status = 0;
        }
        $autoEventsModel = D("AutoEvents");
        $autoCamFileModel = D("AutoCamFile");
//        $productModel = D("Product");
//        $tmpStatus = $productModel->field("isstop")->where("snid = '$obd'")->find();
        $tmpStatus = $status_result['infos'][$obd]['isstop'];

        $json['laststreet'] = $laststreet['address'];
        $json['imagestreet'] = $image['street'];
        $json['cam_stat'] = $cam_stat;
        $json['imageUrl'] = $imageUrl;
        $json['imageTime'] = $imageTime;
        $json['lastTime'] = $lastTime;
        $json['cityCode'] = $cityCode;
        $json['voice_status'] = $voice_status;
        $json['voice_group'] = $json[0]['voice_group'];

        if($tmpStatus['isstop']==1){
            $plate_no = $tmp_arr[0];
            $tmpEvent = $autoEventsModel->field("eventtime,event_id")->where("plate_no = '$plate_no' and class = 0 and type = 1")->order("id desc")->find();
            $tmpImg = $autoCamFileModel->field("file")->where("event_id = '{$tmpEvent['event_id']}'")->find();
            if($tmpImg['file']){
                $json['imageUrl'] = $tmpImg['file'];
                $json['imageTime'] = date("Y-m-d H:i:s",$tmpEvent['eventtime']);
            }
        }

        //查询车辆分组id 语音聊天用
        // $tg_sql="SELECT group_id FROM transport_group_map WHERE obd_no='".$tmp_arr[2]."'";
        // $groupid = M()->query($tg_sql);
        // $json['groupid'] = $groupid[0]['group_id'];
        $userInfo = $_SESSION['_USER_INFO'];
        $json['uid'] = $userInfo['id'];
        echo json_encode($json);die;
    }

    //历史行程（已加）
    function history_path(){
        $inputs = I();
        $obd_no = $inputs['obd_no'];
        $historyDay = $inputs['historyDay'];
        $locusModel = D("AutoTotalLocus");
        if(!$historyDay){
            $lastLocus = $locusModel->field("start_time")->where("obd_no = '$obd_no'")->order("id desc")->find();
            $stime = strtotime(date("Y-m-d 00:00:00",$lastLocus['start_time']));
            $etime = $lastLocus['start_time'];
        }else{
            $stime = strtotime(date("Y-m-d 00:00:00",strtotime($historyDay)));
            $etime = strtotime($historyDay)+3600*24;
        }
        $nowOneDayRes = $locusModel->field("plate_no,start_time,start_addr,end_time,end_addr,(end_time - start_time)/3600 AS duration,total_mileage,total_use_oil,avg_use_oil,avg_kmhour,store_path")->where("start_time >= $stime and start_time <= $etime and obd_no = '$obd_no'")->order("start_time asc")->select();
        $step = 1200;//3秒一条记录，1200条记录，这是60分钟
        //更改数据格式
        foreach($nowOneDayRes as $key=>$value){
            $nowOneDayRes[$key]['start_time'] = date("H:i",$value['start_time']);
            $nowOneDayRes[$key]['end_time'] = date("H:i",$value['end_time']);
            $nowOneDayRes[$key]['duration'] = round($value['duration'],2);//行驶的时间段
            $nowOneDayRes[$key]['total_use_oil'] = $value['total_use_oil']/1000;
            $nowOneDayRes[$key]['avg_use_oil'] = $value['avg_use_oil']/1000;
            $nowOneDayRes[$key]['paths'] = file($value['store_path']);
            $tmp_gps_file = str_replace("\n","",file($value['store_path']));
            $gps = array();
            foreach($tmp_gps_file as $k=>$v){
                $temp_v = explode(',',$v);
                if($temp_v[0] != '4.9E-324' && $temp_v[1] != '4.9E-324' && $temp_v[3] == '61'){
                    $gps[] = $v;
                }
            }
            $nowOneDayRes[$key]['paths'] = $gps;
            $nowOneDayRes[$key]['step'] = $step;
            $nowOneDayRes[$key]['hours'] = ceil(($value['end_time']-$value['start_time'])/($step*3));//分段数

            if($nowOneDayRes[$key]['hours']>1){
                $nowOneDayRes[$key]['locus'] = str_replace("\n","",file($value['store_path']));
                for($i=0;$i<$nowOneDayRes[$key]['hours']-1;$i++){
                    $time = date("H:i",($value['start_time'] + (($i+1)*$step*3)));//中途分段的时间
                    $tmp_arr = explode(",",$nowOneDayRes[$key]['locus'][($i+1)*$step]);

                    $address = json_decode(file_get_contents("https://"),true);
                    if($address['status']==1&&!empty($address['regeocode']['formatted_address'])){
                        if(!empty($address['regeocode']['addressComponent']['township'])){
                            if(!empty($address['regeocode']['addressComponent']['streetNumber']['street'])){
                                $nowOneDayRes[$key]['fp'][] =  array("addr"=>$address['regeocode']['addressComponent']['township'].''.$address['regeocode']['addressComponent']['streetNumber']['street'],"time"=>$time);
                            }else{
                                $nowOneDayRes[$key]['fp'][] =  array("addr"=>$address['regeocode']['addressComponent']['township'],"time"=>$time);
                            }
                        }else{
                            if(!empty($address['regeocode']['addressComponent']['streetNumber']['street'])){
                                $nowOneDayRes[$key]['fp'][] =  array("addr"=>$address['regeocode']['addressComponent']['streetNumber']['street'],"time"=>$time);
                            }else{
                                $nowOneDayRes[$key]['fp'][] =  array("addr"=>'未知',"time"=>$time);
                            }
                        }
                    }else{
                        $nowOneDayRes[$key]['fp'][] =  array("addr"=>'未知',"time"=>$time);
                    }
                }
            }
        }
        $nowOneDayRes['history_time'] = date("Y-m-d",$stime);
        echo json_encode($nowOneDayRes);die;
    }

    //当前行程（已加）
    function now_path(){
        $inputs = I();
        $obd_no = $inputs['obd_no'];
        $autoObdBindModel = D("AutoObdBind");
        $tmpBindInfo = $autoObdBindModel->field("userid,plate_no")->where("obd_no = '$obd_no'")->find();
        $userInfo = $_SESSION["_USER_INFO"];
        $model = M('area','','RBAC_DB_DSN');
        $city = $model->where('id='.$userInfo['area_id'].' and is_show=1')->getField('a_code');

        //历史表中的最后一次上报时间和可视路况表的最后一次上报时间进行比较
        $now_day = date("Y-m-d",time());//当前日期
        //查询可视路况表,获取最后一条数据
        $newdb = M("ActionLog",null,C('LT_DB_DSN'));
        $new_fields = " time_int,speed,lng,lat ";
        $sort = " ORDER BY time_int DESC ";
        $limit = " LIMIT 1 ";
        $new_where = " AND obdid = '".$obd_no."' ";
        $new_where .= $sort;
        $new_where .= $limit;

        // $new_table_name = " `road_cam_bsg_".$city."_".$now_day."` ";

        $time = date('Y-m-d',time());
        $now_time = explode('-', $time);
        $new_table_name =" `data_bsg_all_".$now_time[0].'_'.$now_time[1].'_'.$now_time[2]."` ";

        $new_sql = "SELECT ".$new_fields." FROM ".$new_table_name." WHERE 1=1 ".$new_where." ;";
        $new_result = $newdb->query($new_sql);

        //查询auto_total_locus表
        $carModel = M("Car",null,C('RBAC_DB_DSN'));
        $fields = " plate_no,MAX(inputtime) AS inputtime ";
        $where = " AND obd_no = '".$obd_no."' AND userid = {$tmpBindInfo['userid']} ";
        $table_name = " `auto_total_locus` ";
        $sql = " SELECT ".$fields." FROM ".$table_name." WHERE 1=1 ".$where." ;";
        $result = $carModel->query($sql);
        $plate_no = $result[0]['plate_no'];

        //可视路况的最后一条记录和历史表的最近一条记录的结束时间做比较
        $inputtime = strtotime($result[0]['inputtime']);//历史表最后一次上报时间
        $new_time_int = $new_result[0]['time_int'];//可视路况表最后一次上报时间
        if($new_time_int >= $inputtime){//汽车正在行驶中，显示当前行程
            //查询bsg表
            $now_where ="";
            $now_speed = $new_result[0]['speed'];

            $now_fields = " time_int,time,lng,lat ";
            $now_where .= " AND obdid = '".$obd_no."' ";
            $now_where .= " AND time_int > ".$inputtime." ";
            $now_sort =" ORDER BY time_int ASC ";
            $now_sql = "SELECT ".$now_fields." FROM ".$new_table_name." WHERE 1=1 ".$now_where." ".$now_sort." ;";
            $now_result = $newdb->query($now_sql);
            //行程路径
            $paths = array();
            $i = 0;
            foreach($now_result as $k=>$v){
                $paths[$i]['lng'] = $v['lng'];
                $paths[$i]['lat'] = $v['lat'];
                $i++;
            }

            $duration = ($new_time_int - strtotime($now_result[0]['time']))/3600;//路程时长
            $now_max_time = date("H:i",$new_time_int);
            $now_min_time = date("H:i",strtotime($now_result[0]['time']));
            //开始位置
            $start_gps['lng'] = $now_result[0]['lng'];
            $start_gps['lat'] = $now_result[0]['lat'];
            $address = json_decode(file_get_contents(""),true);
            if($address['status']==1&&!empty($address['regeocode']['formatted_address'])){
                if(!empty($address['regeocode']['addressComponent']['township'])){
                    if(!empty($address['regeocode']['addressComponent']['streetNumber']['street'])){
                        $start_gps['address'] =  $address['regeocode']['addressComponent']['township'].''.$address['regeocode']['addressComponent']['streetNumber']['street'];
                    }else{
                        $start_gps['address'] =  $address['regeocode']['addressComponent']['township'];
                    }
                }else{
                    if(!empty($address['regeocode']['addressComponent']['streetNumber']['street'])){
                        $start_gps['address'] =  $address['regeocode']['addressComponent']['streetNumber']['street'];
                    }else{
                        $start_gps['address'] =  '未知';
                    }
                }
            }else{
                $start_gps['address'] = '未知';
            }

            //结束位置
            $end_gps['lng'] = $new_result[0]['lng'];
            $end_gps['lat'] = $new_result[0]['lat'];
            $address = json_decode(file_get_contents(""),true);
            if($address['status']==1&&!empty($address['regeocode']['formatted_address'])){
                if(!empty($address['regeocode']['addressComponent']['township'])){
                    if(!empty($address['regeocode']['addressComponent']['streetNumber']['street'])){
                        $end_gps['address'] =  $address['regeocode']['addressComponent']['township'].''.$address['regeocode']['addressComponent']['streetNumber']['street'];
                    }else{
                        $end_gps['address'] =  $address['regeocode']['addressComponent']['township'];
                    }
                }else{
                    if(!empty($address['regeocode']['addressComponent']['streetNumber']['street'])){
                        $end_gps['address'] =  $address['regeocode']['addressComponent']['streetNumber']['street'];
                    }else{
                        $end_gps['address'] =  '未知';
                    }
                }
            }else{
                $end_gps['address'] = '未知';
            }

            //当前路径
            $step = 60;//跨度为60分钟
            for($i=0;$i<floor(count($now_result)/$step);$i++){
                $gps[$i]['time'] = date("H:i",$now_result[$i*$step]['time_int']);
                $gps[$i]['lng'] = $now_result[$i*$step]['lng'];
                $gps[$i]['lat'] = $now_result[$i*$step]['lat'];
                $address = json_decode(file_get_contents(""),true);
                if($address['status']==1&&!empty($address['regeocode']['formatted_address'])){
                    if(!empty($address['regeocode']['addressComponent']['township'])){
                        if(!empty($address['regeocode']['addressComponent']['streetNumber']['street'])){
                            $gps[$i]['address'] =  $address['regeocode']['addressComponent']['township'].''.$address['regeocode']['addressComponent']['streetNumber']['street'];
                        }else{
                            $gps[$i]['address'] =  $address['regeocode']['addressComponent']['township'];
                        }
                    }else{
                        if(!empty($address['regeocode']['addressComponent']['streetNumber']['street'])){
                            $gps[$i]['address'] =  $address['regeocode']['addressComponent']['streetNumber']['street'];
                        }else{
                            $gps[$i]['address'] =  '未知';
                        }
                    }
                }else{
                    $gps[$i]['address'] = '未知';
                }
            }
            array_shift($gps);//去掉第一个元素，即开始时间
            if(count($now_result)%$step ==0){
                array_pop($gps);//去掉最后一个元素，即结束时间
            }
            //查询file表
            $file_where = "";
            // $file_table_name = " `road_cam_file_{$city}_".$now_day."` ";

            $time = date('Y-m-d',time());
            $now_time = explode('-', $time);
            $file_table_name =" `data_files_cjc_".$now_time[0].'_'.$now_time[1].'_'.$now_time[2]."` ";

            $file_fields = " COUNT(*) as count";
            $file_where .= " AND obdid = '".$obd_no."' ";
            $file_where .= " AND time_int > ".$inputtime." ";
            $count_image_where = " AND type=1 ";
            $count_video_where = " AND type=2";
            $count_image_sql = "SELECT ".$file_fields." FROM ".$file_table_name." WHERE 1=1 ".$file_where." ".$count_image_where." ;";
            $count_video_sql = "SELECT ".$file_fields." FROM ".$file_table_name." WHERE 1=1 ".$file_where." ".$count_video_where." ;";
            $count_image = $newdb->query($count_image_sql);
            $count_video = $newdb->query($count_video_sql);

//            $file_table_name = " `road_cam_file_tao_".$now_day."` ";
//            $count_image_sql = "SELECT ".$file_fields." FROM ".$file_table_name." WHERE 1=1 ".$file_where." ".$count_image_where." ;";
//            $count_video_sql = "SELECT ".$file_fields." FROM ".$file_table_name." WHERE 1=1 ".$file_where." ".$count_video_where." ;";
//            $count_image2 = $newdb->query($count_image_sql);
//            $count_video2 = $newdb->query($count_video_sql);
//
//            $file_table_name = " `road_cam_file_tna_".$now_day."` ";
//            $count_image_sql = "SELECT ".$file_fields." FROM ".$file_table_name." WHERE 1=1 ".$file_where." ".$count_image_where." ;";
//            $count_video_sql = "SELECT ".$file_fields." FROM ".$file_table_name." WHERE 1=1 ".$file_where." ".$count_video_where." ;";
//            $count_image3 = $newdb->query($count_image_sql);
//            $count_video3 = $newdb->query($count_video_sql);
//
//            $count_image = array_merge($count_image1,$count_image2,$count_image3);
//            $count_video = array_merge($count_video1,$count_video2,$count_video3);

            $details_fields = " lat,lng,gps_addr,speed,file,file_thumb,time ";
            $details_image_sql = "SELECT ".$details_fields." FROM ".$file_table_name." WHERE 1=1 ".$file_where." AND type=1 ;";
            $details_video_sql = "SELECT ".$details_fields." FROM ".$file_table_name." WHERE 1=1 ".$file_where." AND type=2 ;";

            $details_image = $newdb->query($details_image_sql);
            $details_video = $newdb->query($details_video_sql);

            //要显示在页面的数据
            $json_result['status'] = true;//给前台返回，有当前行程
            $json_result['plate_no'] = $plate_no;
            $json_result['refresh'] = $now_max_time;
            $json_result['min_time'] = $now_min_time;
            $json_result['max_time'] = $now_max_time;
            $json_result['start_address'] = $start_gps['address'];
            $json_result['end_address'] = $end_gps['address'];
            $json_result['gps'] = $gps;
            $json_result['duration'] = number_format($duration,2);

            $json_result['count_image'] = $count_image[0]['count'];
            $json_result['count_video'] = $count_video[0]['count'];
            $json_result['details_image'] = $details_image;
            $json_result['details_video'] = $details_video;

            $json_result['now_speed'] = $now_speed;//当前时速
            $json_result['paths'] = $paths;
            $json_result['step'] = $step;
//                  $json_result['track'] = $now_result;

            echo json_encode($json_result);die;
        }else{//汽车已经停止，没有当前行程
            $json_result['status'] = false;//给前台返回，没有当前行程
            echo json_encode($json_result);die;
        }
    }

    //视频直播(已加)
    public function live(){
        $inputs = I();
        $obd_no = $inputs['obd_no'];
        $camid = $inputs['camid'];
        if(!$camid){
//            $ch = curl_init();
//            curl_setopt($ch,CURLOPT_URL,$url);
//            curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
//            curl_setopt($ch,CURLOPT_HEADER,0);
//
//            $output = curl_exec($ch);
//            $content = (array)(json_decode($output));
//            curl_close($ch);
//            $camid = $content['camid'][0];
//----------------------分割线-------------------------------------------

            //获取当前obd设备状态
//            $status_url = 'http:/';//----------测试地址
            $status_url = 'https:';//----------正式地址
            $status_data['obdids'][] = $obd_no;
            $status_result = json_decode(uploadByCURL(json_encode($status_data),$status_url),true);
            if($status_result['result'] == 0){
                $camid = $status_result['infos'][$obd_no]['cam_stat'][0]['id'];
                $last_cam_stat = $status_result['infos'][$obd_no]['last_cam_stat'][0]['id'];
                if($last_cam_stat)
                    $camid = $last_cam_stat;
            }
        }

        if($camid){

            /**
             * [$obd_no description]
             * 执法记录仪
             */
            if($obd_no == 'zf1530027' || $obd_no == 'zf1898249'){
                $popout_url = "https://".$obd_no;
                $live_url = json_decode(file_get_contents($popout_url),true);
                // var_dump($live_url);
                $result['live_url'] = $live_url['url'];
                $result['status'] = 1;
                $result['camid'] = $camid;
                echo json_encode($result);die;                

            }
            /*结束*/
            
            //eventid暂时以'event'加当前时间戳
            $current_time = time();
            $eventid = 'event'.$current_time;
            $popout_url = "https://xxx?camid=".$camid."&eventid=".$eventid."&mediatype=flv&ptype=1&ltime=30";
            // echo $popout_url;
            $live_url = json_decode(file_get_contents($popout_url),true);
            $result['live_url'] = $live_url['url'];
            $result['status'] = 1;
            $result['camid'] = $camid;
            echo json_encode($result);die;
        }else{
            $status = '0';
            $result['status'] = 0;
            echo json_encode($result);die;
        }
    }

    //删除分组处理（已加）
    public function deleteGroupHandle(){
        $id = I("id",'',int);
        $transportGroupMapModel = D("TransportGroupMap");
        $transportGroupModel = D("TransportGroup");
        $groupCarNum = $transportGroupMapModel->field("count(1) num")->where("group_id = $id")->find();//查询分组下面车辆数目
        if($groupCarNum['num']>0){
            echo json_encode(array("status"=>2));die;
        }else{
            $childGroupNum = $transportGroupModel->field("count(1) num")->where("pid = $id")->find();//查询分组下面的子分组数目
            if($childGroupNum['num'] > 0){
                echo json_encode(array("status"=>3));die;
            }
        }

        $r = $transportGroupModel->where("id = $id")->delete();

        if($r){
            echo json_encode(array("status"=>1));
            die;
        }else{
            echo json_encode(array("status"=>0));
            die;
        }
    }

    //移动车辆分组处理(已加)
    public function moveGroupHandle(){
        $groupid = I("groupid",'',int);
        $obdid = I("obdid");
        
        $transportGroupMapModel = D("TransportGroupMap");
        $tmpIs = $transportGroupMapModel->field("id")->where("obd_no='$obdid'")->find();
        if($tmpIs){
            $r = $transportGroupMapModel->save(array("id"=>$tmpIs['id'],"group_id"=>$groupid));
        }else{
            $r = $transportGroupMapModel->add(array("obd_no"=>$obdid,"group_id"=>$groupid));
        }
        if($r){
            echo json_encode(array("status"=>1));
            die;
        }else{
            echo json_encode(array("status"=>0));
            die;
        }
    }

    //添加子分组处理（已加）
    public function addChildGroupHandle(){
        $inputs = I();
        $child_name = urldecode($inputs['child_name']);//接收子分组名称
        $pid = $inputs['pid'];//对应的父级id
        $model = M("transport_group");
/*****查询有没有车辆绑到父级id下，如果有就将所有车辆移动到本分组*****/
        $cars_result = M("transport_group_map")->where("group_id=".$pid)->select();
        $cars_arr = $cars_result[0];//父级id下的车辆数组

//新建子分组
        $data['group_name'] = $child_name;
        $data['status'] = 0;
        $userInfo = $_SESSION["_USER_INFO"];
        $grade = $userInfo['grade'];//用户等级：2是管理员，3是子账户
        if($grade > 2){
            $create_username = $userInfo['create_by'];//string类型
            $p_user_id = M("rbac_user")->where("account='".$create_username."'")->getField('id');//获取创建者id
            $data['uid'] = $p_user_id;//默认可以使用
        }else{
            $data['uid'] = $userInfo['id'];//默认可以使用
        }
//        $data['uid'] = $userInfo['id'];//默认可以使用
        $data['admin_id'] = $userInfo['id'];
        $data['inputtime'] = date("Y-m-d H:i:s",time());
        $data['pid'] = $pid;
        $res = $model->add($data);
        $new_id = $model->getLastInsID();
        if($res){
            $role_id = $userInfo['role_id'];
            M("transport_group_role")->add(array('role_id'=>$role_id,'group_id'=>$new_id));
            if(count($cars_arr)){
                //如果父级id存在车辆，则将车辆都移动到本分组下
                $condition['group_id'] = $new_id;
                $res = M("transport_group_map")->where("group_id=".$pid)->save($condition);
                if(res){
                    echo $new_id;
                }else{
                    $model->delete($new_id);//删除新创建的分组
                    echo "false";
                }
            }else{
                echo $new_id;
            }
        }else{
            echo "false";
        }
    }

    //车辆实时追踪，一分钟请求一次，每次查询最近一条记录，把bsg字段的6个坐标读出来
   function trace(){
        $obd_no = I('obd_no');
        // $cityCode = I('cityCode'); // 定位的城市代码
        // $userInfo = $_SESSION["_USER_INFO"];
        // $now_day = date("Y-m-d",time());//当前日期
        // //查询可视路况表,获取最后一条数据
        $time = date('Y-m-d',time());
        $now_time = explode('-', $time);
        $newdb = M("'data_bsg_all_'.$now_time[0].'_'.$now_time[1].'_'.$now_time[2]",null,C('LT_DB_DSN'));
        $new_fields = " id,time_int,speed,bsg ";
        $new_where = " AND obdid = '".$obd_no."' ";

        $new_where .= " order by id desc limit 1";
       
        // var_dump($now_time);die;
        $new_sql = "SELECT ".$new_fields." FROM `data_bsg_all_".$now_time[0].'_'.$now_time[1].'_'.$now_time[2]."` WHERE 1=1 ".$new_where." ;";
        // if($cityCode && $cityCode != 'null'){
        //     $city = $cityCode;
        // }else{
        //     //判断查询的城市表
        //     $model = M('area','','RBAC_DB_DSN');
        //     $city = $model->where('id='.$userInfo['area_id'].' and is_show=1')->getField('a_code');            
        // }
        
        // $new_table_name = " `road_cam_bsg_".strtolower($city)."_".$now_day."` ";

        // $new_city_sql = "SELECT ".$new_fields." FROM ".$new_table_name." WHERE 1=1 ".$new_where." ;";//先查城市表
        // $new_city_result = $newdb->query($new_city_sql);
       
        // //如果城市表中存在数据，并且时间在30分钟内，直接返回，否则查询other表
        // if( (time() - $new_city_result[0]['time_int']) < 10*60 ){
        //     $new_result = $new_city_result;            
        // }else{
        $new_result = $newdb->query($new_sql);
            // $new_result = $new_other_result;
        // }
        // echo $new_sql;
        // var_dump($new_result);die;
        
        echo json_encode($new_result[0]);die;
    }

    //刷新当前左侧分组车辆的状态
    public function refresh_cars_status(){
        $group_arr = explode(',',I('groups'));
        $userInfo = $_SESSION["_USER_INFO"];
        $model = M();
        foreach ($group_arr as $k => $groupId) {
            if($groupId != '0') {
                //判断是否有子分组
                if ($userInfo['role_id'] != 87) {
                    $arr_sql = "select tg.id,group_name from `transport_group` tg
                            join `transport_group_role` tgr on tgr.group_id = tg.id
                            where pid=" . $groupId . " and tgr.role_id = {$userInfo['role_id']};";
                } else {
                    $arr_sql = "select tg.id,group_name from `transport_group` tg
                            where pid=" . $groupId . ";";
                }
                $arr_result = $model->query($arr_sql);
                if (count($arr_result)) {
                    continue;//存在子分组，直接跳过
                }
            }
//不存在子分组，直接返回车辆
            if ($userInfo['role_id'] != 87) {
                $cars_sql = "select aob.obd_no,p.isstop from product p
                join auto_obd_bind aob on aob.obd_no = p.snid
                left join auto_user au on au.id = aob.userid
                left join transport_group_map tgm on tgm.obd_no = aob.obd_no
                left join transport_group tg on tg.id = tgm.group_id
                join transport_group_role tgr on tgm.group_id = tgr.group_id
                where tgr.role_id = {$userInfo['role_id']} ";
            } else {
                $cars_sql = "select aob.obd_no,p.isstop from product p
                join auto_obd_bind aob on aob.obd_no = p.snid
                left join auto_user au on au.id = aob.userid
                left join transport_group_map tgm on tgm.obd_no = aob.obd_no
                left join transport_group tg on tg.id = tgm.group_id
                where p.uid = {$userInfo['id']}";
            }

            if ($groupId != 0) {
                $cars_sql .= " and tgm.group_id = {$groupId}; ";
            } else {
                $cars_sql .= " and aob.obd_no not in(select obd_no from product p join transport_group_map tgm on p.snid = tgm.obd_no where tgm.group_id>0); ";
            }
            $cars_result = $model->query($cars_sql);

            foreach ($cars_result as $key => $value){
                $obd_arr[] = $value['obd_no'];
            }
            
            $obd = array_chunk($obd_arr,100);
            
            foreach($obd as $item){
                //获取当前obd设备状态
    //            $status_url = 'http://';//----------测试地址
                $status_url = 'https://';//----------正式地址
                $status_data['obdids'] = $item;
                $status_result = json_decode(uploadByCURL(json_encode($status_data),$status_url),true);
                if($status_result['result'] == 0){
                    $json_arr[0]['voice_group_all'] = 0;//组默认不显示公聊按钮
                    foreach($cars_result as $key => $value){
                        $json_arr[$key]['obd_no'] = $value['obd_no'];
                        foreach($status_result['infos'] as $k => $v){
                            if($k == $value['obd_no']){
                                if($v['isstop'] == 0){//点火状态
                                    $json_arr[$key]['car_status'] = '0';//运行状态
                                    $json_arr[$key]['isstop'] = 0;
                                    $json_arr[0]['voice_group_all'] = 1;
                                }else{
                                    $json_arr[$key]['car_status'] = '1';//停运状态
                                    $json_arr[$key]['isstop'] = 1;
                                }
                                if($v['last_start_time_int'] < time()-180){//如果3分钟没收到心跳
                                    $json_arr[$key]['car_status'] = '2';//离线状态
                                }
                            }
                        }
                        $json_content[] = $json_arr[$key];
                    }
                }else{
                    foreach($cars_result as $key => $value){
                        $json_arr[$key]['obd_no'] = $value['obd_no'];
                        $json_arr[$key]['car_status'] = '2';//离线
                        $json_content[] = $json_arr[$key];
                    }
                }
            }


//            //获取redis设备存活最新时间
//            $obd_up_time['db'] = "up_redis_sync_W";
//            $obd_up_time['cmd'] = "hmget";
//            $obd_up_time['args'] = $obd_arr;
//            $obd_up_res = json_decode(uploadByCURL(json_encode($obd_up_time), "http://"), true);//接口返回两个值：result和data,result=0表示命令已经执行，data的值是返回obd最后一次心跳时间戳   （如果cmd=hmget，可以批量获取obd的最后一次心跳时间，obd数组集合）心跳时间理论一分钟一次，时间过长为掉线
//
//            foreach ($cars_result as $key => $value){
//                $json_arr[$key]['obd_no'] = $value['obd_no'];
//                if($obd_up_res['result'] == 0){
//                    if($value['isstop'] == '0') {
//                        $json_arr[$key]['car_status'] = '0';//运行状态
//                    }else{
//                        $json_arr[$key]['car_status'] = '1';//停运状态
//                    }
//                    if($obd_up_res['data'][$key] < (time()-180)){//如果3分钟没收到心跳
//                        $json_arr[$key]['car_status'] = '2';//离线状态
//                    }
//                }else{
//                    $json_arr[$key]['car_status'] = '2';//离线状态
//                }
//                $json_content[] = $json_arr[$key];
//            }
        }
        echo json_encode($json_content);
        die;
    }

    public function ai_demo(){
        $this->display();
    }

    //语音
    public function micro(){
        $model = M();
        $roomId = I('roomId');
        $userInfo=$_SESSION['_USER_INFO'];
        if($roomId && ($roomId<100000000000000)){
                $arr_sql = "select tg.uid,tg.id from `transport_group` tg
                            join `rbac_user` ru on tg.uid = ru.id
                            where ru.account='" . $userInfo['account']."' and tg.id = ".$roomId;
                $arr_result = $model->query($arr_sql);
                $room_name = $arr_result['0']['uid'].'_'.$arr_result['0']['id'];
                $room_user_sql = "select obd_no from `transport_group_map` where group_id = ".$arr_result['0']['id'];
                $room_user_result = $model->query($room_user_sql);
                foreach($room_user_result as $key => $val){
                    $plate_no_sql = "select plate_no from `auto_obd_bind` where obd_no = ".$val['obd_no'];
                    $plate_no_result = $model->query($plate_no_sql);
                    $room_user[$key]['plate_no'] = $plate_no_result[0]['plate_no'];
                    $room_user[$key]['obd_no'] = $val['obd_no'];
                }
                $this->room_user = $room_user;
        }else{
                $arr_sql = "select id from `rbac_user` where account='" . $userInfo['account']."'";
                $arr_result = $model->query($arr_sql);
                if($roomId){
                    $room_name = "private_".$arr_result['0']['id'].'_'.$roomId;
                    $plate_no_sql = "select plate_no from `auto_obd_bind` where obd_no = ".$roomId;
                    $plate_no_result = $model->query($plate_no_sql);
                    $this->plate_no = $plate_no_result['0']['plate_no'];
                }else{
                    $room_name = $arr_result['0']['id'].'_'.$roomId;
                }
        }
        //执法记录仪（演示后删除） zsn
        $zf_key = substr( $roomId, 0, 1 );
        if($userInfo['account']=='zsqcd'&&$zf_key=='z'){
            $room_name = 'private_'.$userInfo['id'].'_'.$roomId;
        }
        //执法记录仪end
        $this->roomName = $room_name;
        $this->display();
    }

    public function outagelist(){
        $inputs = I();
        $model = new Model();
        $userInfo = $_SESSION["_USER_INFO"];
        
        //判断用户所属城市地区，对前台页面做不同处理
        if($userInfo['area_id']==2){
            $this->areaChk = "北京市";
        }else{
            $this->areaChk = "山东省";
        }

        //查询当前用户角色
        $role_sql = "SELECT role_id FROM rbac_role_user WHERE user_id =".$userInfo['id'];
        $role_id = M()->query($role_sql);
        $role_id = $role_id[0]['role_id'];
        // var_dump($role_id);die;
        /**
         * [$role_id description]
         * role_id=87 平台创建的一级账号
         * role_id不等于87  一级账号创建的子账号，后续查询要根据角色id去过滤车辆分组
         */
        if($role_id == 87 ){
            if(isset($inputs['offgroup'])&&intval($inputs['offgroup'])!=1){
                if(intval($inputs['offgroup'])==0){
                    $cars_sql = "SELECT aob.plate_no,au.username,aob.obd_no,tgm.remark FROM product p 
                                JOIN auto_obd_bind aob ON aob.obd_no = p.snid 
                                LEFT JOIN auto_user au ON au.id  = aob.userid 
                                LEFT JOIN transport_group_map tgm ON tgm.obd_no = aob.obd_no 
                                LEFT JOIN transport_group tg ON tg.id  = tgm.group_id WHERE p.uid = {$userInfo['id']} 
                                AND aob.obd_no NOT IN(
                                SELECT obd_no FROM product p JOIN transport_group_map tgm ON p.snid = tgm.obd_no WHERE tgm.group_id>0
                                )";
                }else{
                    $temp_offgroup = intval($inputs['offgroup']);
                    $cars_sql = "select aob.plate_no,au.username,aob.obd_no,tgm.remark,tg.group_name,tgm.group_id from product p
                                join auto_obd_bind aob on aob.obd_no = p.snid
                                left join auto_user au on au.id = aob.userid
                                left join transport_group_map tgm on tgm.obd_no = aob.obd_no
                                left join transport_group tg on tg.id = tgm.group_id
                                where tgm.group_id = {$temp_offgroup} and p.uid = {$userInfo['id']} order by tg.group_name"; 
                }
            }else{
                    $cars_sql = "select aob.plate_no,au.username,aob.obd_no,tgm.remark,tg.group_name,tgm.group_id from product p
                                join auto_obd_bind aob on aob.obd_no = p.snid
                                left join auto_user au on au.id = aob.userid
                                left join transport_group_map tgm on tgm.obd_no = aob.obd_no
                                left join transport_group tg on tg.id = tgm.group_id
                                where p.uid = {$userInfo['id']} order by tg.group_name";                  
               }
            if($inputs['orderName']==3){
                if(isset($inputs['offgroup'])&&intval($inputs['offgroup'])!=1){
                    if(intval($inputs['offgroup'])==0){
                        $cars_sql = "SELECT aob.plate_no,au.username,aob.obd_no,tgm.remark FROM product p 
                                    JOIN auto_obd_bind aob ON aob.obd_no = p.snid 
                                    LEFT JOIN auto_user au ON au.id  = aob.userid 
                                    LEFT JOIN transport_group_map tgm ON tgm.obd_no = aob.obd_no 
                                    LEFT JOIN transport_group tg ON tg.id  = tgm.group_id WHERE p.uid = {$userInfo['id']} 
                                    AND aob.obd_no NOT IN(
                                    SELECT obd_no FROM product p JOIN transport_group_map tgm ON p.snid = tgm.obd_no WHERE tgm.group_id>0
                                    )";
                    }else{
                        $temp_offgroup = intval($inputs['offgroup']);
                        $cars_sql = "select aob.plate_no,au.username,aob.obd_no,tgm.remark,tg.group_name,tgm.group_id from product p
                                join auto_obd_bind aob on aob.obd_no = p.snid
                                left join auto_user au on au.id = aob.userid
                                left join transport_group_map tgm on tgm.obd_no = aob.obd_no
                                left join transport_group tg on tg.id = tgm.group_id
                                where tgm.group_id = {$temp_offgroup} and p.uid = {$userInfo['id']} order by tg.group_name";
                    }
                }else{
                    $cars_sql = "select aob.plate_no,au.username,aob.obd_no,tgm.remark,tg.group_name,tgm.group_id from product p
                            join auto_obd_bind aob on aob.obd_no = p.snid
                            left join auto_user au on au.id = aob.userid
                            left join transport_group_map tgm on tgm.obd_no = aob.obd_no
                            left join transport_group tg on tg.id = tgm.group_id
                            where p.uid = {$userInfo['id']} order by tg.group_name";                    
                }
            } //等于87
        }else{ //不等于87
            //取出角色下分组，根据分组取车辆
            $group_sql = "SELECT group_id FROM transport_group_role WHERE role_id = ".$role_id."";
            $group_arr = M()->query($group_sql);
            $group_new = array();
            foreach($group_arr as $k => $v){
                $group_new[] = $v['group_id'];
            }
            $group_new = implode(',',$group_new);
            // var_dump($group_new);die;
            if(isset($inputs['offgroup'])&&intval($inputs['offgroup'])!=1){
                if(intval($inputs['offgroup'])==0){
                    $cars_sql = "SELECT aob.plate_no,au.username,aob.obd_no,tgm.remark FROM product p 
                                JOIN auto_obd_bind aob ON aob.obd_no = p.snid 
                                LEFT JOIN auto_user au ON au.id  = aob.userid 
                                LEFT JOIN transport_group_map tgm ON tgm.obd_no = aob.obd_no 
                                LEFT JOIN transport_group tg ON tg.id  = tgm.group_id WHERE tg.id IN (".$group_new.")
                                AND aob.obd_no NOT IN(
                                SELECT obd_no FROM product p JOIN transport_group_map tgm ON p.snid = tgm.obd_no WHERE tgm.group_id>0
                                )";
                }else{
                    $temp_offgroup = intval($inputs['offgroup']);
                    $cars_sql = "select aob.plate_no,au.username,aob.obd_no,tgm.remark,tg.group_name,tgm.group_id from product p
                                join auto_obd_bind aob on aob.obd_no = p.snid
                                left join auto_user au on au.id = aob.userid
                                left join transport_group_map tgm on tgm.obd_no = aob.obd_no
                                left join transport_group tg on tg.id = tgm.group_id
                                where tgm.group_id = {$temp_offgroup} and tg.id IN (".$group_new.") order by tg.group_name"; 
                }
            }else{
                    $cars_sql = "select aob.plate_no,au.username,aob.obd_no,tgm.remark,tg.group_name,tgm.group_id from product p
                                join auto_obd_bind aob on aob.obd_no = p.snid
                                left join auto_user au on au.id = aob.userid
                                left join transport_group_map tgm on tgm.obd_no = aob.obd_no
                                left join transport_group tg on tg.id = tgm.group_id
                                where tg.id IN (".$group_new.") order by tg.group_name";                  
               }
            if($inputs['orderName']==3){
                if(isset($inputs['offgroup'])&&intval($inputs['offgroup'])!=1){
                    if(intval($inputs['offgroup'])==0){
                        $cars_sql = "SELECT aob.plate_no,au.username,aob.obd_no,tgm.remark FROM product p 
                                    JOIN auto_obd_bind aob ON aob.obd_no = p.snid 
                                    LEFT JOIN auto_user au ON au.id  = aob.userid 
                                    LEFT JOIN transport_group_map tgm ON tgm.obd_no = aob.obd_no 
                                    LEFT JOIN transport_group tg ON tg.id  = tgm.group_id WHERE tg.id IN (".$group_new.") 
                                    AND aob.obd_no NOT IN(
                                    SELECT obd_no FROM product p JOIN transport_group_map tgm ON p.snid = tgm.obd_no WHERE tgm.group_id>0
                                    )";
                    }else{
                        $temp_offgroup = intval($inputs['offgroup']);
                        $cars_sql = "select aob.plate_no,au.username,aob.obd_no,tgm.remark,tg.group_name,tgm.group_id from product p
                                join auto_obd_bind aob on aob.obd_no = p.snid
                                left join auto_user au on au.id = aob.userid
                                left join transport_group_map tgm on tgm.obd_no = aob.obd_no
                                left join transport_group tg on tg.id = tgm.group_id
                                where tgm.group_id = {$temp_offgroup} and tg.id IN (".$group_new.") order by tg.group_name";
                    }
                }else{
                    $cars_sql = "select aob.plate_no,au.username,aob.obd_no,tgm.remark,tg.group_name,tgm.group_id from product p
                            join auto_obd_bind aob on aob.obd_no = p.snid
                            left join auto_user au on au.id = aob.userid
                            left join transport_group_map tgm on tgm.obd_no = aob.obd_no
                            left join transport_group tg on tg.id = tgm.group_id
                            where tg.id IN (".$group_new.") order by tg.group_name";                    
                }
            }
        }

        $cars_result = $model->query($cars_sql);
        // echo $model->getLastSQL();
        // var_dump($cars_result);
        foreach($cars_result as $key => $value){
            $obd_arr[] = $value['obd_no'];
        }
        $obd = array_chunk($obd_arr,100);
        // var_dump($obd);
        $stop_cars_result;
        foreach($obd as $item){
            //获取当前obd设备状态
            $status_url = 'https://';//----------正式地址
            $status_data['obdids'] = $item;
            $status_result = json_decode(uploadByCURL(json_encode($status_data),$status_url),true);
            if($status_result['result'] == 0){
                 foreach($cars_result as $key => $value){
                     foreach($status_result['infos'] as $k => $v){
                         if($k == $value['obd_no']){
                             if($v['last_start_time_int'] < time()-180){//如果3分钟没收到心跳
                                 $cars_result[$key]['car_status'] = '2';//离线状态
                                 $timestamp = $v['last_start_time']?strtotime($v['last_start_time']):0;
                                 $off_time = time() - $timestamp;
                                 if($off_time > 172799){
                                    if($off_time > 31103999){
                                        $month = $off_time/31104000;
                                        // $cars_result[$key]['last_start_time'] = floor($month).'年前';
                                        $cars_result[$key]['last_start_time'] = '1年前';//大于一年时统一显示一年
                                     }elseif ($off_time > 2591999){
                                        $month = $off_time/2592000;
                                        $cars_result[$key]['last_start_time'] = floor($month).'月前';
                                     }elseif ($off_time > 86399) {
                                         $day = $off_time/86400;
                                         $cars_result[$key]['last_start_time'] = floor($day).'日前';
                                     }
                                     if(intval($inputs['offtime'])==0){
                                         $cars_result[$key]['last_start_time_int'] = $v['last_start_time_int'];
                                         $stop_cars_result[] = $cars_result[$key];
                                     }elseif($off_time > intval($inputs['offtime'])){
                                         $cars_result[$key]['last_start_time_int'] = $v['last_start_time_int'];
                                         $stop_cars_result[] = $cars_result[$key];
                                     }
                                 }
                             } 
                         }
                     }
                 }
            } 
        }
        // var_dump($stop_cars_result);
        $cars_result = $stop_cars_result;
        

        //获取obd最后位置上报信息
        $timestamp = time();
        $token = 'A#tomic@Soner'.$timestamp;
        if(!empty($obd_arr))
            $result = uploadByCURL(json_encode(array('obdids' =>$obd_arr,'token' =>$token)),"https://");
        $temp = json_decode($result,true);
        foreach($cars_result as $key => $value){
            foreach($temp['list'] as $k1 => $v1){
                if($value['obd_no'] == $v1['id']){
                    $mapPosition = $temp["list"][$k1]["lg"]?explode(",",$temp["list"][$k1]["lg"]):explode(",",$temp["list"][$k1]["g"]);
                    $position = $temp['list'][$k1]['rs']?$temp['list'][$k1]['rs']:'';
                    $lng = $mapPosition[1];  //存储一份 经度纬度位置信息，当接口没有返回值时引用
                    $lat = $mapPosition[0];
                    $cars_result[$key]['position'] = $temp['list'][$k1]['rs']?$temp['list'][$k1]['rs']:'';//车辆当前地理位置
                    $cars_result[$key]['lng'] = $mapPosition[1];//车辆当前坐标经度
                    $cars_result[$key]['lat'] = $mapPosition[0];//车辆当前坐标纬度
                    $cars_result[$key]['lastTime'] = $temp['list'][$k1]['lt']?urldecode($temp['list'][$key]['lt']):urldecode($temp['list'][$k1]['t']);//车辆当前坐标汇报时间
                }
            }
            
        }
        foreach ($cars_result as $k2 => $v2){
            if(!isset($v2['lng'])){
                $cars_result[$k2]['lng'] = $lng;
                $cars_result[$k2]['lat'] = $lat;
                $cars_result[$k2]['position'] = $position;
            }
        }




        if($role_id == 87 ){
            //全部分组
            $groups_sql ="SELECT id,group_name FROM transport_group 
                WHERE id NOT IN (
                SELECT pid FROM transport_group WHERE pid IN 
                    (
                        SELECT id FROM transport_group WHERE pid = 0 AND uid = {$userInfo['id']}
                    ) 
                AND uid = {$userInfo['id']}
                ) 
                AND uid = {$userInfo['id']}";
        }else{
            $groups_sql = "SELECT id,group_name FROM transport_group WHERE id IN (".$group_new.") AND id NOT IN (SELECT pid FROM transport_group WHERE pid IN (".$group_new.") )";
        }
 
        $groups_result = $model->query($groups_sql);

        // die;


        //信息有：plate_no,username,obd_no,isstop,remark,position,lng,lat,car_status，lastTime, group_name,group_id
        if($inputs['orderName']){
            $temp;
            if($inputs['orderName']==1){
                for($i=0;$i<count($cars_result)-1;$i++ ){       
                    for($j=0;$j<count($cars_result)-1-$i;$j++){ 
                        if($cars_result[$j]['last_start_time_int'] < $cars_result[$j+1]['last_start_time_int']){
                            $temp = $cars_result[$j];
                            $cars_result[$j] = $cars_result[$j+1];
                            $cars_result[$j+1] = $temp;
                        } 
                    }
                }
            }elseif($inputs['orderName']==2){
                $temp;
                for($i=0;$i<count($cars_result)-1;$i++ ){       
                    for($j=0;$j<count($cars_result)-1-$i;$j++){ 
                        if($cars_result[$j]['last_start_time_int'] > $cars_result[$j+1]['last_start_time_int']){
                            $temp = $cars_result[$j];
                            $cars_result[$j] = $cars_result[$j+1];
                            $cars_result[$j+1] = $temp;
                        } 
                    }
                }
            }
            echo json_encode($cars_result);die();
        }
        // var_dump($cars_result);
        $temp;
        for($i=0;$i<count($cars_result)-1;$i++ ){       
            for($j=0;$j<count($cars_result)-1-$i;$j++){ 
                if($cars_result[$j]['last_start_time_int'] < $cars_result[$j+1]['last_start_time_int']){
                    $temp = $cars_result[$j];
                    $cars_result[$j] = $cars_result[$j+1];
                    $cars_result[$j+1] = $temp;
                } 
            }
        }
        $temp_group = isset($inputs['offgroup'])?1:0;
        if($off_time > intval($inputs['offtime'])&&intval($inputs['offtime'])!=0||intval($inputs['offtime'])!=0||$temp_group){
             echo json_encode($cars_result);die();
         }
        $this->outagelist = $cars_result?json_encode($cars_result):'';
        $this->groupslist = $groups_result;
        $this->display();
    }   
}